#include "led_app.h"
#include <rtthread.h>
#include <rtdevice.h>
#include "n32g45x_gpio.h"

#define LED_THREAD_PRIORITY     25
#define LED_THREAD_STACK_SIZE   288
#define LED_THREAD_TIMESLICE    5

static rt_thread_t led_tid  = RT_NULL;

/* defined the LED1 pin: PB5 */
#define LED1_PIN    67      // PA8
#define LED2_PIN    90      // PB4
#define LED3_PIN    91      // PB5

static void led_init(void)
{
    RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_AFIO,ENABLE);
    GPIO_ConfigPinRemap(GPIO_RMP_SW_JTAG_SW_ENABLE, ENABLE);
    /* set LED1 pin mode to output */
    rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED2_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED3_PIN, PIN_MODE_OUTPUT);
}

static void led_app_entry(void* para)
{
    uint32_t Speed = 500;

    if (para != RT_NULL) {
        Speed = (uint32_t)(*(uint32_t*)para);
    }

    rt_kprintf("Speed = %d\r\n", Speed);

    led_init();

    while (1)
    {
        rt_pin_write(LED1_PIN, PIN_LOW);
        rt_pin_write(LED2_PIN, PIN_HIGH);
        rt_pin_write(LED3_PIN, PIN_LOW);
        rt_thread_mdelay(Speed);
        rt_pin_write(LED1_PIN, PIN_HIGH);
        rt_pin_write(LED2_PIN, PIN_LOW);
        rt_pin_write(LED3_PIN, PIN_HIGH);
        rt_thread_mdelay(Speed);
    }
}

void led_app(void)
{
//    uint32_t led_blink_freq = 1000;
    led_tid = rt_thread_create("led_app",
                                led_app_entry, RT_NULL,
                                LED_THREAD_STACK_SIZE,
                                LED_THREAD_PRIORITY, LED_THREAD_TIMESLICE);
    if (led_tid != RT_NULL){
        rt_thread_startup(led_tid);
    }
}

MSH_CMD_EXPORT(led_app, led sample);
